<!--  -->
<template>
  <div class="maxbg">
    <transition name="fade">
      <div class="pageBody g-bg">
        <div class="dt-top pay-head">
          <div class="back" @click="goback">返回</div>
          <div class="tl">支付页</div>
          <div class="down-btn" @click="linkCourse">下载APP</div>
        </div>
        <div class="pay-main">
          <div class="order-infor">
            <div class="order-tl">支付金额</div>
            <div class="order-money">
              <span style="font-size: 0.48rem">¥&nbsp;</span
              >{{ (vipOrderInfo.amountActually / 1000).toFixed(2) }}
            </div>
            <div class="order-tip">购买会员</div>
          </div>
          <div class="pay-infor">
            <div class="pay-type">选择支付方式</div>
            <div class="pay-box">
              <div
                class="pay-gp wechat"
                :class="[payType == 'wechat' ? 'on' : '']"
                @click="pay('wechat')"
              >
                微信支付
              </div>
              <div
                class="pay-gp alipay"
                :class="[payType == 'alipay' ? 'on' : '']"
                @click="pay('alipay')"
              >
                支付宝支付
              </div>
            </div>
          </div>
        </div>
        <div class="pay-order-btn" @click="payOrder">确认支付</div>
      </div>
    </transition>
  </div>
  <div class="mask" v-if="isShowModal">
    <div class="modal">
      <div class="moadl-tl">提示</div>
      <div class="modal-tx">购买成功，请前往APP学习</div>
      <div class="modal-btn" @click="goback">知道了</div>
    </div>
  </div>
  <div class="mask" v-if="paySuccess">
    <div class="modal">
      <div class="moadl-tl">提示</div>
      <div class="modal-tx">支付成功</div>
      <div class="modal-btn" @click="gotoBack">知道了</div>
    </div>
  </div>
  <div class="mask" v-if="isWxAlipay" @click="isWxAlipay = false">
    <div class="gotoWeb"></div>
  </div>
</template>

<script>
import { os } from "@/utils/base.js";
import wx from "weixin-js-sdk";

export default {
  data() {
    return {
      vipOrderInfo: {
        amountActually: 0,
      },
      payType: "wechat",
      paySuccess: false,
      isWxAlipay: false,
    };
  },
  components: {},
  created() {
    this.init();
  },
  mounted() {
    this.getOrderInfor();
  },

  methods: {
    gotoBack() {
      // this.$router.push({ path: "/question", query: { id: courseId } });
      const code = this.$route.query.invitationCode
        ? this.$route.query.invitationCode
        : "";
      const cardId = this.$route.query.id ? this.$route.query.id : "";
      const actionType = this.$route.query.actionType
        ? this.$route.query.actionType
        : "";
      const type = this.$route.query.type ? this.$route.query.type : "";
      window.location.href =
        "/h5/vip?actionType=" +
        actionType +
        "&invitationCode=" +
        code +
        "&id=" +
        cardId +
        "&type=" +
        type;
    },
    pay(name) {
      this.payType = name;
    },
    getOrderInfor() {
      const orderId = this.$route.query.orderId;
      const type = this.$route.query.type;
      if (orderId) {
        this.orderId = orderId;
        this.getCommodityState();
      } else {
        if (type == 1) {
          this.vipPlaceOrder();
        }
      }
    },
    goback() {
      this.$router.go(-1);
    },
    // 生成订单
    vipPlaceOrder() {
      const params = {
        cardId: this.$route.query.id,
        agentCode: this.$route.query.invitationCode
          ? this.$route.query.invitationCode
          : null,
      };
      this.$http
        .vipPlaceOrder(params)
        .then((res) => {
          if (res.flag == 0) {
            this.orderId = res.data.id;
            this.vipOrderInfo = res.data || null;
          }
        })
        .catch((err) => {
          // ElMessage.error(err.response.data.message);
        });
    },
    payOrder() {
      this.payVipOrder();
    },
    payVipOrder() {
      const orderId = this.$route.query.orderId;
      const obj = {
        payway: this.payType == "wechat" ? 2 : 3,
        orderId: this.orderId,
        payType: 2,
      };
      if (os.weixin) {
        obj.payType = 3;
        obj.wxJsapiCode = sessionStorage.getItem("wxCode");
      }
      if (this.payType == "alipay") {
        obj.rtnUrl = window.location.href + "&orderId=" + this.orderId;
      } else {
        obj.wxH5Type = "充值余额";
      }
      this.$http
        .payVipOrder(obj)
        .then((res) => {
          if (res.flag == 0) {
            if (this.payType == "wechat") {
              const url = encodeURIComponent(
                window.location.href + "&orderId=" + this.orderId
              );
              if (os.weixin) {
                this.initWXPay(res.data.wechatpayBody);
              } else {
                window.location.href =
                  res.data.wechatpayBody.h5_url + "&redirect_url=" + url;
              }
            } else {
              if (os.weixin) {
                this.isWxAlipay = true;
              } else {
                window.location.href =
                  "https://openapi.alipay.com/gateway.do?" + res.data.body;
              }
            }
            // this.getCommodityState();
          }
        })
        .catch((err) => {
          console.log(err.response.data.message);
        });
    },
    initWXPay(config) {
      const that = this;
      wx.config({
        debug: false,
        appId: config.appId,
        timestamp: config.timeStamp,
        nonceStr: config.nonceStr,
        signature: config.signature,
        jsApiList: ["chooseWXPay"],
      });

      wx.ready(() => {
        // 微信支付配置完成后，调用支付函数
        wx.chooseWXPay({
          timestamp: config.timeStamp,
          nonceStr: config.nonceStr,
          package: config.packageValue,
          signType: config.signType,
          paySign: config.paySign,
          success: function (res) {
            // 支付成功的回调
            that.paySuccess =true;
          },
          fail: function (res) {
            // 支付失败的回调
          },
          complete: (res) => {
            if (res.errMsg == "chooseWXPay:ok") {
              // 回调函数内容
              that.paySuccess =true;
            }
          },
        });
      });
    },
    getCommodityState() {
      this.$http
        .getVipStatus(this.orderId)
        .then((res) => {
          if (res.flag == 0) {
            if ((res.data & 0x2) != 0) {
              this.paySuccess = true;
            } else {
              this.vipPlaceOrder();
            }
          }
        })
        .catch((err) => {
          console.log(err.response.data.message);
        });
    },
    init() {
      const s = document.createElement("script");
      s.type = "text/javascript";
      s.src = "//web.cdn.openinstall.io/openinstall.js";
      s.addEventListener(
        "load",
        () => {
          var data = OpenInstall.parseUrlParams();
          new OpenInstall(
            {
              appKey: "zpyiil", //appkey参数配置,需要自行替换对应的appkey
              onready: function () {
                var m = this;
                /*在app已安装的情况尝试拉起app*/
                m.schemeWakeup({
                  data: data,
                  channelCode: "test-channelcode",
                });
                window.wakeupOrInstall = function () {
                  this.rnum = this.rnum + 1;
                  m.wakeupOrInstall({
                    data: data,
                    channelCode: "test-channelcode",
                  });
                };
              },
            },
            data
          );
        },
        false
      );
      document.head.appendChild(s);
    },
    linkCourse() {
      // alert('下载课程')
      // console.log(1212)
      window.wakeupOrInstall(); //此方法为scheme、Universal Link唤醒以及引导下载的作用（必须调用且不可额外自行跳转下载）
      return false;
    },
  },
};
</script>

<style lang='scss' scoped>
</style>
